import re
import subprocess

import html2image
import qrcode

from config import mos_attestat_print_folder


def generate_attestat_face(
        name="Ельцин Борис Николаевич",
        date='27.06.2024',
        school='ЦПШ Тиксинского района р. Саха (Якутия) с углублённым изучением чукотского языка',
        year='2024',
        director='Шеварднадзе Эдуард Хабибнурмагомедович',
        attestat_number='12345678901234',
        is_necessary_to_print_back=True,
        **kwargs
):
    code = open('templates/attestat-face-template.html', 'r').read()
    if not is_necessary_to_print_back:
        code = code.replace(
            '<img src="file:///PROJECT_FOLDER_PLACEHOLDER/blancs/attestat-nofields.jpg" id="back">', ''
        )

    code = code.replace(
        'DATE_PLACEHOLDER', date
    ).replace(
        'NAME_PLACEHOLDER', name
    ).replace(
        'SCHOOL_PLACEHOLDER', school
    ).replace(
        'YEAR_PLACEHOLDER', year
    ).replace(
        'DIRECTOR_PLACEHOLDER', director
    ).replace(
        'PROJECT_FOLDER_PLACEHOLDER', mos_attestat_print_folder
    )
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(f'{name.replace(" ", "|")}|Москва|{attestat_number}|{date}')
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    subprocess.run(['mkdir', '-p', 'qrcodes'])
    img.save(f'qrcodes/{name}.png')

    code = code.replace('QR_PLACEHOLDER', name)

    with open('test1.html', 'w') as out:
        out.write(code)
    hti = html2image.Html2Image()
    hti.size = (832, 586)
    hti.output_path = f'{mos_attestat_print_folder}/faces'
    hti.screenshot(url=f'{mos_attestat_print_folder}/test1.html',
                   save_as=f'{attestat_number}-{name}.png')


def generate_attestat_attachment(
        name="Ельцин Борис Николаевич",
        date='27.06.2024',
        birthday='01.02.1931',
        director='Шеварднадзе Эдуард Хабибнурмагомедович',
        attestat_number='12345678901234',
        info='',
        is_necessary_to_print_back=True,
        **kwargs
):
    code = open('templates/attestat-attachment-template.html', 'r').read()
    if not is_necessary_to_print_back:
        code = code.replace(
            '<img id="back" src="file:///PROJECT_FOLDER_PLACEHOLDER/blancs/attachment-1.jpg">', ''
        )
    code = code.replace(
        'DATE_PLACEHOLDER', date
    ).replace(
        'NAME_PLACEHOLDER', name
    ).replace(
        'BIRTHDAY_PLACEHOLDER', birthday
    ).replace(
        'DIRECTOR_PLACEHOLDER', director
    ).replace(
        'NUMBER_PLACEHOLDER', attestat_number
    ).replace(
        'INFO_PLACEHOLDER', info.replace(';', '<br>')
    ).replace(
        'PROJECT_FOLDER_PLACEHOLDER', mos_attestat_print_folder
    )

    with open('test1.html', 'w') as out:
        out.write(code)
    hti = html2image.Html2Image()
    hti.size = (1096, 775)
    hti.output_path = f'{mos_attestat_print_folder}/attachments'
    hti.screenshot(url=f'{mos_attestat_print_folder}/test1.html',
                   save_as=f'{attestat_number}-{name}.png')


def generate_attestat_marks(
        name="Ельцин Борис Николаевич",
        attestat_number='12345678901234',
        marks=None,
        is_necessary_to_print_back=True,
        **kwargs
):
    if marks is None:
        marks = {}
    marks_meanings = {
        '2': '2 (плохо)',
        '3': '3 (удовл.)',
        '4': '4 (хор.)',
        '5': '5 (отл.)'
    }
    code = open('templates/attestat-marks-template.html', 'r').read()
    if not is_necessary_to_print_back:
        code = code.replace(
            '<img src="file:///PROJECT_FOLDER_PLACEHOLDER/blancs/marks.jpg" id="back">', ''
        )
    table_height, row_height = 0, 0
    max_rows = 18
    for row in code.split('\n'):
        if 'tr-height' in row:
            row_height = int(re.findall(r'\d+', row)[0])
        if 'table-height' in row:
            table_height = int(re.findall(r'\d+', row)[0])
    if table_height > 0 and row_height > 0:
        max_rows = table_height // row_height
    for key in marks.keys():
        if marks[key] in marks_meanings:
            marks[key] = marks_meanings[marks[key]]
    marks_code = ''
    marks2_code = ''
    marks_cnt = 0
    for mark in marks:
        if marks[mark]:
            marks_cnt += 1
            if marks_cnt <= max_rows:
                marks_code += f'<tr><td>{mark}</td><td>{marks[mark]}</td></tr>'
            elif marks_cnt <= max_rows * 2:
                marks2_code += f'<tr><td>{mark}</td><td>{marks[mark]}</td></tr>'
    code = code.replace(
        'MARKS_PLACEHOLDER', marks_code).replace(
        'MARKS2_PLACEHOLDER', marks2_code
    ).replace(
        'PROJECT_FOLDER_PLACEHOLDER', mos_attestat_print_folder
    )

    with open('test1.html', 'w') as out:
        out.write(code)
    hti = html2image.Html2Image()
    hti.size = (1096, 775)
    hti.output_path = f'{mos_attestat_print_folder}/marks'
    hti.screenshot(url=f'{mos_attestat_print_folder}/test1.html',
                   save_as=f'{attestat_number}-{name}.png')
